<template>
    <section>
        <el-col :span="24">
            <el-form inline>
                <el-form-item>
                    <el-input size="small" placeholder="合同编号" v-model.trim="form.factory_contract_no" style="width: 250px" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="form.supplier_id" filterable remote placeholder="输入搜索的工厂名称" size="small"
                               :remote-method="searchFactoryBtn" :loading="searchLoading" clearable :disabled="user.source_from=='gc'">
                        <el-option v-for="(item,index) in factoryList" :label="item.factory_name" :value="item.supplier_id" :key="index">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-popover placement="bottom" width="450" trigger="click">
                        <el-form label-width="90px" label-position="left">
                            <el-form-item label="品牌类型">
                                <el-select v-model="form.brand_code" placeholder="品牌" size="small" style="width: 80%" clearable>
                                    <el-option value="S" label="十三余"></el-option>
                                    <el-option value="Y" label="有香"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="加工单号">
                                <el-input size="small" v-model.trim="form.processing_code" placeholder="加工单" style="width: 80%;" clearable></el-input>
                            </el-form-item>
                        </el-form>
                        <el-button slot="reference" size="small" type="warning" plain>更多</el-button>
                    </el-popover>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="el-icon-search" @click="searchBtn" size="small" :loading="btnLoading">查询</el-button>
                </el-form-item>
            </el-form>
        </el-col>
        <el-col :span="24">
            <el-table :data="data" style="width: 100%" :max-height="tableHeight" v-loading="loading" size="mini">
                <el-table-column label="合同编号" prop="factory_contract_no" width="180"></el-table-column>
                <el-table-column label="工厂" prop="factory_name" show-overflow-tooltip></el-table-column>
                <el-table-column label="加工单号" prop="processing_code" width="150"></el-table-column>
                <el-table-column label="款号" prop="type_no" width="130"></el-table-column>
                <el-table-column label="合同金额" prop="contract_amount"></el-table-column>
                <el-table-column label="总件数" prop="totalnum" width="80"></el-table-column>
                <el-table-column label="违约赔偿" prop="fine_amount" width="90">
                    <template slot-scope="{ row }">
                        <el-button v-if="row.fine_amount>0" size="mini" type="text" @click="linkTo('soa_fine', row.factory_contract_no)">{{ row.fine_amount }}</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="额外费用" prop="additional_amount" width="90">
                    <template slot-scope="{ row }">
                        <el-button v-if="row.additional_amount>0" size="mini" type="text" @click="linkTo('soa_extra', row.factory_contract_no)">{{ row.additional_amount }}</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="合同时间" prop="contract_date" width="130"></el-table-column>
                <el-table-column label="理单员" prop="order_processor" width="90"></el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="{ row }">
                        <el-tag size="mini" type="success" v-if="row.status==2">已通过</el-tag>
                        <el-tag size="mini" type="info" v-else>{{row.status}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="申请" width="150" fixed="right" v-if="user.source_from=='fs'">
                    <template slot-scope="{ row }">
                        <el-button type="text" size="mini" @click="applyBtn('fine', row)" :disabled="!(row.status==2 && nodeActions.includes('apply'))">违约赔偿</el-button>
                        <el-button type="text" size="mini" @click="applyBtn('extra', row)" :disabled="!(row.status==2 && nodeActions.includes('apply'))">额外费用</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--翻页栏-->
            <div style="margin-top: 4px;overflow: hidden;float: right;">
                <Page :total="total" :current="page" :page-size="limit" show-total @on-change="pageChange"></Page>
            </div>
        </el-col>

        <!--申请违约赔偿-->
        <el-drawer title="申请违约赔偿" :visible.sync="fineVisible" size="600px" direction="rtl" :wrapperClosable="false" :before-close="closeBtn">
            <el-row style="padding-left: 20px;padding-bottom:20px;overflow-y:auto;" :style="{'height': drawHeight}">
                <el-form :rules="applyFormRule" :model="applyForm" label-position="left" label-width="90px">
                    <el-form-item label="合同编号">
                        <el-input size="small" :value="applyForm.factory_contract_no" style="width: 90%" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="款号">
                        <el-input size="small" :value="applyForm.type_no" style="width: 90%" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="工厂名称" prop="supplier_id">
                        <el-select v-model="applyForm.supplier_id" filterable remote placeholder="输入搜索的工厂名称" size="small" style="width: 90%"
                                   :remote-method="searchFactoryBtn" :loading="searchLoading" clearable>
                            <el-option v-for="(item,index) in factoryList" :label="item.factory_name" :value="item.supplier_id" :key="index">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="赔偿原因" prop="reason">
                        <el-select size="small" v-model="applyForm.reason" style="width: 90%">
                            <el-option value="逾期" label="逾期"></el-option>
                            <el-option value="其他" label="其他"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="赔偿金额" prop="amount">
                        <el-input size="small" v-model.trim="applyForm.amount" type="number" style="width: 90%" placeholder="请输入违约赔偿金额"></el-input>
                    </el-form-item>
                    <el-form-item label="赔偿备注" prop="remarks">
                        <el-input size="small" v-model.trim="applyForm.remarks" type="textarea" :row="2" style="width: 90%" placeholder="请输入违约赔偿备注"></el-input>
                    </el-form-item>
                    <el-form-item label="上传凭证" prop="images">
                        <el-upload action="/api/tool/fileImport" list-type="picture-card"
                                   :headers="uploadHeaders"
                                   :data="uploadData"
                                   :file-list="this.applyForm.images"
                                   :on-success="(res, file, fileList)=>uploadSuccessHandle(res, fileList)"
                                   :before-upload="beforeUploadHandle">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                                <span class="el-upload-list__item-actions">
<!--                        <span class="el-upload-list__item-preview" @click="previewImgBtn(file)">-->
                                    <!--                          <i class="el-icon-zoom-in"></i>-->
                                    <!--                        </span>-->
                        <span class="el-upload-list__item-delete" @click="delImgBtn(file)">
                          <i class="el-icon-delete"></i>
                        </span>
                    </span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-row>
            <div style="width: 100%;position: absolute;bottom: 10px;padding: 8px;border-top: 1px #ebeef5 solid;">
                <el-button type="primary" @click="closeBtn" plain>退出</el-button>
                <el-button type="primary" @click="submitFineBtn" :loading="btnLoading">{{btnLoading ? "申请中..." : "确认"}}</el-button>
            </div>
        </el-drawer>

        <!--申请额外费用-->
        <el-drawer title="申请额外费用" :visible.sync="extraVisible" size="600px" direction="rtl" :wrapperClosable="false" :before-close="closeBtn">
            <el-row style="padding-left: 20px;padding-bottom:20px;overflow-y:auto;" :style="{'height': drawHeight}">
                <el-form :rules="applyFormRule" :model="applyForm" label-position="left" label-width="90px">
                    <el-form-item label="合同编号">
                        <el-input size="small" :value="applyForm.factory_contract_no" style="width: 90%" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="款号">
                        <el-input size="small" :value="applyForm.type_no" style="width: 90%" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="工厂名称" prop="supplier_id">
                        <el-select v-model="applyForm.supplier_id" filterable remote placeholder="输入搜索的工厂名称" size="small" style="width: 90%"
                                   :remote-method="searchFactoryBtn" :loading="searchLoading" clearable>
                            <el-option v-for="(item,index) in factoryList" :label="item.factory_name" :value="item.supplier_id" :key="index">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用途" prop="purpose">
                        <el-select size="small" v-model="applyForm.purpose" style="width: 90%" placeholder="请选择用途">
                            <el-option value="修色费" label="修色费"></el-option>
                            <el-option value="包缸染色费" label="包缸染色费"></el-option>
                            <el-option value="水洗固色色费" label="水洗固色色费"></el-option>
                            <el-option value="运输费" label="运输费"></el-option>
                            <el-option value="维修费（更换吊牌洗标）" label="维修费（更换吊牌洗标）"></el-option>
                            <el-option value="其他" label="其他"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="单价" prop="price">
                        <el-input size="small" v-model.trim="applyForm.price" @change="priceChange" type="number" style="width: 90%" placeholder="请输入单价"></el-input>
                    </el-form-item>
                    <el-form-item label="数量" prop="num">
                        <el-input size="small" v-model.trim="applyForm.num" @change="priceChange" type="number" style="width: 90%" placeholder="请输入数量"></el-input>
                    </el-form-item>
                    <el-form-item label="税率" prop="tax_rate">
                        <el-input size="small" v-model.trim="applyForm.tax_rate" @change="priceChange" type="number" style="width: 90%" placeholder="请输入税率">
                            <template slot="append">%</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="总价" prop="amount">
                        <el-input size="small" :value="applyForm.amount" type="number" style="width: 90%" placeholder="总价" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="备注" prop="remarks">
                        <el-input size="small" v-model.trim="applyForm.remarks" type="textarea" :row="2" style="width: 90%" placeholder="请输入违约赔偿备注"></el-input>
                    </el-form-item>
                    <el-form-item label="上传凭证" prop="images">
                        <el-upload action="/api/tool/fileImport" list-type="picture-card"
                                   :headers="uploadHeaders"
                                   :data="uploadData"
                                   :file-list="this.applyForm.images"
                                   :on-success="(res, file, fileList)=>uploadSuccessHandle(res, fileList)"
                                   :before-upload="beforeUploadHandle">
                            <i slot="default" class="el-icon-plus"></i>
                            <div slot="file" slot-scope="{file}">
                                <img class="el-upload-list__item-thumbnail" :src="file.url" />
                                <span class="el-upload-list__item-actions">
<!--                        <span class="el-upload-list__item-preview" @click="previewImgBtn(file)">-->
                                    <!--                          <i class="el-icon-zoom-in"></i>-->
                                    <!--                        </span>-->
                        <span class="el-upload-list__item-delete" @click="delImgBtn(file)">
                          <i class="el-icon-delete"></i>
                        </span>
                    </span>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-row>
            <div style="width: 100%;position: absolute;bottom: 10px;padding: 8px;border-top: 1px #ebeef5 solid;">
                <el-button type="primary" @click="closeBtn" plain>退出</el-button>
                <el-button type="primary" @click="submitExtraBtn" :loading="btnLoading">{{btnLoading ? "申请中..." : "确认"}}</el-button>
            </div>
        </el-drawer>
    </section>
</template>

<script>

import {factoryList} from "@/api/produce/factory";
import {contractListXh} from "@/api/soa/contract";
import {getToken} from "@/libs/util";
import {fineCreate} from "@/api/soa/fine";
import {extraCreate} from "@/api/soa/extra";

export default {
    name: "soa_xh_contract",
    data() {
        return {
            tableHeight: window.innerHeight - 210,
            selectIndex: 0,
            btnLoading: false,
            loading: false,
            page: 1,
            limit: 20,
            total: 0,
            data: [],
            user: {},
            nodeActions: [],

            form: {processing_code: "", factory_contract_no: "", supplier_id: "", brand_code: ""},
            searchLoading: false,
            factoryList: [],

            drawHeight: window.innerHeight - 150+"px",
            fineVisible:false,
            extraVisible: false,
            applyForm: {images: []},
            applyFormRule: {
                supplier_id: [{ required: true, trigger: "blur" }],
                reason: [{required: true, trigger: "blur"}],
                amount: [{required: true, trigger: "blur"}],
                remarks: [{required: true, trigger: "blur"}],
                purpose: [{required: true, trigger: "blur"}],
                price: [{required: true, trigger: "blur"}],
                num: [{required: true, trigger: "blur"}],
                tax_rate: [{required: true, trigger: "blur"}],
                images: [{required: true, trigger: "blur"}],
            },

            uploadHeaders: {},
            uploadData:{type: 'soa_xh_contract', disk: 'image'},
        }
    },
    created() {
        this.user = this.$store.getters.user;
        this.nodeActions = this.user.node_actions[this.$route.meta.id] ? this.user.node_actions[this.$route.meta.id] : [];
        if(this.user.source_from == 'gc'){//用户来源：工厂
            this.form.supplier_id = this.user.supplier_id;
        }
    },
    methods: {
        //搜索加工厂
        searchFactoryBtn(val){
            if(val == ""){
                return;
            }
            this.getFactoryData(val);
        },
        getFactoryData(name){
            factoryList({page: 1, limit: 100, tab: 2, factory_name: name, status: 0}).then((res) =>{
                this.factoryList = res.data.data;
            })
        },
        //搜索按钮
        searchBtn() {
            this.page = 1;
            this.getData();
        },
        //翻页
        pageChange(page) {
            this.page = page;
            this.getData();
        },
        //获取数据
        getData() {
            let param = {
                page: this.page,
                limit: this.limit
            };
            param = Object.assign(param, this.form)
            this.loading = true;
            contractListXh(param).then((res) => {
                this.loading = false;
                this.total = res.data.total;
                this.data = res.data.data;
            }).catch(() => {
                this.loading = false;
            });
        },
        //跳转
        linkTo(name, no){
            this.$router.push({
                name: name,
                params: {factory_contract_no: no}
            })
        },
        closeBtn(){
            this.applyForm = {images: []};
            this.fineVisible = false;
            this.extraVisible = false;
        },
        //打开申请
        applyBtn(type, row){
            if(type == 'fine'){
                this.fineVisible = true;
                this.applyForm = {
                    factory_contract_no:row.factory_contract_no,
                    type_no: row.type_no,
                    source_factory_groups_id: row.source_factory_groups_id,
                    order_processor: row.order_processor,
                    supplier_id: "",
                    reason: "",
                    amount: "",
                    remarks:"",
                    images: []
                };
            }
            if(type == 'extra'){
                this.extraVisible = true;
                this.applyForm = {
                    factory_contract_no:row.factory_contract_no,
                    type_no: row.type_no,
                    source_factory_groups_id: row.source_factory_groups_id,
                    order_processor: row.order_processor,
                    supplier_id: "",
                    purpose: "",
                    price: "",
                    num: "",
                    tax_rate: "",
                    tax_rate_price: "",
                    amount: "",
                    images: []
                };
            }
        },
        priceChange(){
            let amount = 0;
            let taxRatePrice = 0;
            if (this.applyForm.num && this.applyForm.price && this.applyForm.tax_rate) {
                amount = (Number(this.applyForm.price) * Number(this.applyForm.num) * (Number(this.applyForm.tax_rate)/100 + 1)).toFixed(2);
                taxRatePrice = (Number(this.applyForm.price) * Number(this.applyForm.num) * Number(this.applyForm.tax_rate)/100).toFixed(2);
            }
            this.$set(this.applyForm, 'amount', amount);
            this.$set(this.applyForm, 'tax_rate_price', taxRatePrice)
        },
        //提交申请--违约赔偿
        submitFineBtn(){
            if(!this.applyForm.supplier_id || !this.applyForm.reason || !this.applyForm.amount || !this.applyForm.remarks || this.applyForm.images.length==0){
                this.$message.warning("必填信息不能为空!");return;
            }
            let obj = JSON.parse(JSON.stringify(this.applyForm));
            obj.images = [];
            this.applyForm.images.forEach(item =>{
                obj.images.push(item.response.data);
            })
            this.btnLoading = true;
            fineCreate(obj).then((res) =>{
                this.btnLoading = false;
                if(res.code === 0){
                    this.$message.success(res.msg);
                    this.closeBtn();
                }else{
                    this.$message.error(res.msg);
                }
            }).catch(() =>{
                this.btnLoading = false;
            })
        },
        //提交申请--额外费用
        submitExtraBtn(){
            if(!this.applyForm.supplier_id || !this.applyForm.purpose || !this.applyForm.price || !this.applyForm.num || !this.applyForm.tax_rate
                || !this.applyForm.amount || this.applyForm.images.length==0){
                this.$message.warning("必填信息不能为空!");return;
            }
            let obj = JSON.parse(JSON.stringify(this.applyForm));
            obj.images = [];
            this.applyForm.images.forEach(item =>{
                obj.images.push(item.response.data);
            })
            this.btnLoading = true;
            extraCreate(obj).then((res) =>{
                this.btnLoading = false;
                if(res.code === 0){
                    this.$message.success(res.msg);
                    this.closeBtn();
                }else{
                    this.$message.error(res.msg);
                }
            }).catch(() =>{
                this.btnLoading = false;
            })
        },

        //删除图片
        delImgBtn(file){
            let index;
            for(let i in this.applyForm.images){
                if(this.applyForm.images[i].uid == file.uid){
                    index = i;
                    break;
                }
            }
            if(index != undefined){
                this.applyForm.images.splice(index, 1);
            }
        },
        //上传之前的检测
        beforeUploadHandle(file) {
            if(!['image/jpg','image/jpeg','image/png'].includes(file.type)){
                this.$message.error('上传图片只能是 jpg、png 格式!');
                return false;
            }
            this.uploadHeaders.Authorization = 'Bearer '+ getToken();
            return true;
        },
        //上传成功
        uploadSuccessHandle(res, fileList) {
            if(res.code === 0){
                this.$set(this.applyForm, 'images', fileList);
            }else{
                this.$message.error("上传失败");
                fileList = fileList.filter(item => item.response && item.response.code === 0);
                this.$set(this.applyForm, 'images', fileList);
            }
        },
    },
    mounted() {
        this.getFactoryData("");
        this.searchBtn();
    }
}
</script>

<style scoped>

</style>
